import { createI18n } from 'vue-i18n'
import type { I18n, I18nOptions } from 'vue-i18n'
import { LanguageEnum } from '@renderer/enums/SettingEnum'
import { App } from 'vue'

// 动态导入语言文件
const messages = {
  [LanguageEnum.EN]: () => import('./locales/en.json'),
  [LanguageEnum.SIMPLE_ZH]: () => import('./locales/zh.json')
}

// 语言选项
export const languageOptions = [
  { value: LanguageEnum.SIMPLE_ZH, label: '简体中文' },
  { value: LanguageEnum.EN, label: 'English' }
]

const i18nOptions: I18nOptions = {
  locale: LanguageEnum.SIMPLE_ZH,
  legacy: false,
  globalInjection: true,
  fallbackLocale: LanguageEnum.SIMPLE_ZH,
  messages: {}
}

const i18n: I18n = createI18n(i18nOptions)

// 异步加载语言文件
Object.keys(messages).forEach((locale) => {
  ;(messages as Record<string, () => Promise<any>>)[locale]().then((msg) => {
    i18n.global.setLocaleMessage(locale, msg.default)
  })
})

interface Translation {
  (key: string): string
}

export const $t = i18n.global.t as Translation

// 全局注册 i18n
export function setupI18n(app: App<Element>) {
  app.use(i18n)
}

export default i18n
